package com.xdxc.filter;

import com.xdxc.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            try {
                // 解析 JWT
                Claims claims = JWTUtil.extractAllClaims(token.substring(7));
                if (claims.getExpiration().before(new Date())) {
                    throw new RuntimeException("Token expired");
                }
                // 获取用户名和角色
                String username = claims.getSubject();
                List<String> roles = (List<String>) claims.get("roles");
                Long userId = claims.get("userId", Long.class); // 获取用户ID
                // 创建 Authentication 对象
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        roles.stream()
                                .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) // 关键修改
                                .collect(Collectors.toList())
                );
                Map<String, Object> details = new HashMap<>();

                details.put("userId", userId); // 存储用户ID
                details.put("token", token.substring(7)); // 存储原始 Token
                authentication.setDetails(details);
                // 设置到 SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception e) {
                // 如果解析失败，可能是无效的 JWT
                SecurityContextHolder.clearContext();
            }
        }
        // 继续处理请求
        filterChain.doFilter(request, response);
    }
}